package com.taotao.search.dao.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.taotao.search.dao.SearchDao;
import com.taotao.search.pojo.SearchItem;
import com.taotao.search.pojo.SearchResult;

@Repository
public class SearchDaoImpl implements SearchDao {

	@Autowired
	private HttpSolrServer httpSolrServer;

	@Override
	public SearchResult search(SolrQuery query) throws Exception {

		QueryResponse response = httpSolrServer.query(query);
		SolrDocumentList documentList = response.getResults();
		SearchResult result = new SearchResult();

		// 取高亮信息
		Map<String, Map<String, List<String>>> highlighting = response
				.getHighlighting();
		List<SearchItem> itemList = new ArrayList<SearchItem>();

		for (SolrDocument solrDocument : documentList) {
			SearchItem item = new SearchItem();
			item.setId((String) solrDocument.get("id"));
			item.setCategory_name((String) solrDocument
					.get("item_category_name"));
			item.setId((String) solrDocument.get("id"));
			item.setImage((String) solrDocument.get("item_image"));
			item.setPrice(solrDocument.get("item_price").toString());
			item.setSell_point((String) solrDocument.get("item_sell_point"));
			List<String> highList = highlighting.get(solrDocument.get("id"))
					.get("item_title");
			// 判断是否有高亮信息
			if (highList != null && highList.size() > 0) {
				item.setTitle(highList.get(0));
			} else {
				item.setTitle((String) solrDocument.get("item_title"));
			}
			itemList.add(item);

		}
		result.setItemList(itemList);
		// 设置总条数
		result.setTotal(documentList.getNumFound());
		return result;
	}

}
